package top.ajun.mall.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ajun.common.to.SkuReductionTo;
import top.ajun.common.to.SpuBoundTo;
import top.ajun.common.utils.PageUtils;
import top.ajun.common.utils.Query;
import top.ajun.common.utils.R;
import top.ajun.mall.product.dao.SpuInfoDao;
import top.ajun.mall.product.entity.AttrEntity;
import top.ajun.mall.product.entity.ProductAttrValueEntity;
import top.ajun.mall.product.entity.SkuImagesEntity;
import top.ajun.mall.product.entity.SkuInfoEntity;
import top.ajun.mall.product.entity.SkuSaleAttrValueEntity;
import top.ajun.mall.product.entity.SpuInfoDescEntity;
import top.ajun.mall.product.entity.SpuInfoEntity;
import top.ajun.mall.product.feign.CouponFeignService;
import top.ajun.mall.product.service.AttrService;
import top.ajun.mall.product.service.ProductAttrValueService;
import top.ajun.mall.product.service.SkuImagesService;
import top.ajun.mall.product.service.SkuInfoService;
import top.ajun.mall.product.service.SkuSaleAttrValueService;
import top.ajun.mall.product.service.SpuImagesService;
import top.ajun.mall.product.service.SpuInfoDescService;
import top.ajun.mall.product.service.SpuInfoService;
import top.ajun.mall.product.vo.Attr;
import top.ajun.mall.product.vo.BaseAttrs;
import top.ajun.mall.product.vo.Bounds;
import top.ajun.mall.product.vo.Images;
import top.ajun.mall.product.vo.Skus;
import top.ajun.mall.product.vo.SpuSaveVo;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
            new Query<SpuInfoEntity>().getPage(params),
            Wrappers.query()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = Wrappers.lambdaQuery();

        // 检索关键字
        String key = (String) params.get("key");
        if (StrUtil.isNotEmpty(key)) {
            wrapper.and(w -> w.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key));
        }

        // 商品状态
        String status = (String) params.get("status");
        if (StrUtil.isNotEmpty(status)) {
            wrapper.eq(SpuInfoEntity::getPublishStatus, status);
        }

        // 品牌id 
        String brandId = (String) params.get("brandId");
        if (StrUtil.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq(SpuInfoEntity::getBrandId, brandId);
        }

        // 三级分类id
        String catelogId = (String) params.get("catelogId");
        if (StrUtil.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq(SpuInfoEntity::getCatalogId, catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 保存 Spu 的基本信息: pms_spu_info
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfo);
        spuInfo.setCreateTime(new Date());
        spuInfo.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfo);

        // 保存 Spu 的描述信息: pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDesc = new SpuInfoDescEntity();
        spuInfoDesc.setSpuId(spuInfo.getId());
        spuInfoDesc.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDesc);

        // 保存 Spu 的图片集: pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfo.getId(), images);

        // 保存 Spu 的规格参数: pms_product_attr_value
        List<BaseAttrs> baseAttrList = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueList = baseAttrList.stream().map(attr -> {
            ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
            productAttrValue.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValue.setAttrName(attrEntity.getAttrName());
            productAttrValue.setAttrValue(attr.getAttrValues());
            productAttrValue.setQuickShow(attr.getShowDesc());
            productAttrValue.setSpuId(spuInfo.getId());
            return productAttrValue;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttrValue(productAttrValueList);

        // 保存 Spu 的积分信息(远程服务调用): mall_sms => sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfo.getId());
        R spuResp = couponFeignService.saveSpuBounds(spuBoundTo);
        if (spuResp.getCode() != 0) {
            log.error("远程保存 Spu 积分信息失败");
        }

        // 保存 Spu 对应的的所有 Sku 信息
        List<Skus> skuList = spuSaveVo.getSkus();
        if (CollUtil.isEmpty(skuList)) {
            return;
        }
        skuList.forEach(sku -> {
            String defaultImg = "";
            for (Images img : sku.getImages()) {
                if (img.getDefaultImg() == 1) {
                    defaultImg = img.getImgUrl();
                }
            }

            // 保存 Sku 的基本信息: pms_sku_info
            SkuInfoEntity skuInfo = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfo);
            skuInfo.setBrandId(spuInfo.getBrandId());
            skuInfo.setCatalogId(spuInfo.getCatalogId());
            skuInfo.setSaleCount(0L);
            skuInfo.setSpuId(spuInfo.getId());
            skuInfo.setSkuDefaultImg(defaultImg);
            skuInfoService.saveSkuInfo(skuInfo);
            // sku id 自增主键
            Long skuId = skuInfo.getSkuId();

            // 保存 Sku 的图片信息: pms_sku_images
            List<SkuImagesEntity> skuImageList = sku.getImages().stream().map(img -> {
                SkuImagesEntity skuImage = new SkuImagesEntity();
                skuImage.setSkuId(skuId);
                skuImage.setImgUrl(img.getImgUrl());
                skuImage.setDefaultImg(img.getDefaultImg());
                return skuImage;
            }).filter(img -> StrUtil.isNotEmpty(img.getImgUrl())).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImageList);

            // 保存 Sku 的销售属性: pms_sku_sale_attr_value
            List<Attr> attrList = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueList = attrList.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValue = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValue);
                skuSaleAttrValue.setSkuId(skuId);
                return skuSaleAttrValue;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueList);

            // 保存 Sku 的打折, 满减信息, 会员价格(远程服务调用): mall_sms => sms_sku_ladder, sms_sku_full_reduction, sms_member_price
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(sku, skuReductionTo);
            skuReductionTo.setSkuId(skuId);
            if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {
                R skuResp = couponFeignService.saveSkuReduction(skuReductionTo);
                if (skuResp.getCode() != 0) {
                    log.error("远程保存 Sku 优惠信息失败");
                }
            }
        });
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfo) {
        this.baseMapper.insert(spuInfo);
    }

}